package com.hongyu.smart.village.ui.activity;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;

import androidx.media3.common.MediaItem;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.datasource.rtmp.RtmpDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.hls.HlsMediaSource;
import androidx.media3.exoplayer.rtsp.RtspMediaSource;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.ui.PlayerView;

import com.hongyu.smart.village.R;
import com.hongyu.smart.village.event.Event;
import com.hongyu.smart.village.ui.base.BaseActivity;

public class WebVedioPlayActivity extends BaseActivity {
    private ExoPlayer mPlayer; // 声明一个新型播放器对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    protected void initActivityData() {
        PlayerView pv_content = findViewById(R.id.pv_content);
        mPlayer = new ExoPlayer.Builder(this).build();
        pv_content.setPlayer(mPlayer); // 设置播放器视图的播放器对象
        playVideo(Uri.parse("https://storage.googleapis.com/exoplayer-test-media-1/mp4/dizzy-with-tx3g.mp4"));
    }

    @Override
    protected void initContentView() {

    }

    @Override
    protected int getContentView() {
        return R.layout.activity_web_vedio_play;
    }

    @Override
    protected void onEventProcess(Event event) {

    }


    // 播放视频
    @SuppressLint("UnsafeOptInUsageError")
    private void playVideo(Uri uri) {
        DataSource.Factory factory = new DefaultDataSource.Factory(this);
        // 创建指定地址的媒体对象
        MediaItem videoItem = new MediaItem.Builder().setUri(uri).build();
        // 基于工厂对象和媒体对象创建媒体来源
        MediaSource videoSource;
        if (uri.getPath().endsWith("m3u8")) { // hls链接
            videoSource = new HlsMediaSource.Factory(factory)
                    .createMediaSource(videoItem);
        } else if (uri.getPath().startsWith("rtsp")) { // rtsp链接
            videoSource = new RtspMediaSource.Factory()
                    .createMediaSource(videoItem);
        } else if (uri.getPath().startsWith("rtmp")) { // rtmp链接
            videoSource = new ProgressiveMediaSource.Factory(new RtmpDataSource.Factory())
                    .createMediaSource(videoItem);
        } else { // 其他链接（http开头或https开头的普通视频链接）
            videoSource = new ProgressiveMediaSource.Factory(factory)
                    .createMediaSource(videoItem);
        }
        mPlayer.setMediaSource(videoSource); // 设置播放器的媒体来源
        mPlayer.prepare(); // 播放器准备就绪
        mPlayer.play(); // 播放器开始播放
    }
}